package org.iartisan.maven.plugin.handle;

import org.apache.maven.plugin.logging.Log;
import org.iartisan.maven.plugin.exception.InvalidCommandException;
import org.iartisan.maven.plugin.log.LoggerFactory;
import org.iartisan.maven.plugin.mavenconfig.*;
import org.iartisan.maven.plugin.template.TemplateParse;

import java.io.IOException;
import java.util.Arrays;

/**
 * <p>
 * 命令接收
 *
 * @author King
 * @since 2017/9/15
 */
public class CommandExecutor {

    private TemplateConfig templateConfig;

    private BaseConfig baseConfig;

    private DataSourceConfig dataSourceConfig;

    private TableConfig tableConfig;

    private DaoPackageConfig daoConfig;

    private PackageConfig serviceConfig;

    private PackageConfig controllerConfig;

    private PackageConfig htmlPageConfig;

    private String[] commands = new String[]{"all", "service", "controller", "dao", "html"};

    private TemplateParse templateParse = new TemplateParse();

    protected static Log logger = LoggerFactory.getLogger();

    public CommandExecutor(TemplateConfig templateConfig, BaseConfig baseConfig, DataSourceConfig dataSourceConfig, TableConfig tableConfig, DaoPackageConfig daoConfig, PackageConfig serviceConfig, PackageConfig controllerConfig, PackageConfig htmlPageConfig) {
        this.templateConfig = templateConfig;
        this.baseConfig = baseConfig;
        this.dataSourceConfig = dataSourceConfig;
        this.tableConfig = tableConfig;
        this.daoConfig = daoConfig;
        this.serviceConfig = serviceConfig;
        this.controllerConfig = controllerConfig;
        this.htmlPageConfig = htmlPageConfig;
    }

    public void execute(String command) {
        try {
            if (null == baseConfig) {
                logger.error("请添baseConfig配置");
                return;
            }
            //判断command 是否为有效命令
            if (!Arrays.asList(commands).contains(command)) {
                throw new InvalidCommandException("无效的命令:" + command);
            }
            //初始化模版
            templateParse.initConfiguration(templateConfig);
            if (command.equals("dao")) {
                DaoGenerateHandler.doGenerate(templateParse, baseConfig, tableConfig, dataSourceConfig, daoConfig);
            }
            String osName = System.getProperty("os.name");
            if (osName != null) {
                if (osName.contains("Mac")) {
                    Runtime.getRuntime().exec("open " + baseConfig.getDirectory());
                } else if (osName.contains("Windows")) {
                    Runtime.getRuntime().exec("cmd /c start " + baseConfig.getDirectory());
                } else {
                    System.err.println("save dir:" + baseConfig.getDirectory());
                }
            }
            logger.info("代码生成完成!!!");
        } catch (Exception e) {
            logger.info("代码生成异常:", e);
        }
    }
}
